package com.qiangqiang.service;

import com.qiangqiang.cache.RedisClient;
import com.qiangqiang.entity.DorStu;
import com.qiangqiang.enums.DorStuEnum;
import com.qiangqiang.exception.DorStuException;
import com.qiangqiang.repository.DorStuReposity;
import com.qiangqiang.repository.StudentRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by q on 2018/2/5.
 */
@Slf4j
@Service
public class DorStuService {

    @Autowired
    private DorStuReposity dorStuRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private RedisClient client;

    boolean flag=false;

    /**
     * 增加或更新一条记录
     *
     * @param dorStu
     * @return
     */
    @Transactional
    public DorStu addOrUpdateRelationShip(DorStu dorStu) {
        String key="stu:"+dorStu.getDId();
        //如果在缓存中存在该key ，则在缓存中要加上该学生
        if(client.isExistKey(key)){
            System.out.println("命中");
            client.push(key,studentRepository.queryBySId(dorStu.getSId()));
        }
        DorStu objDorStu = dorStuRepository.queryBySId(dorStu.getSId());
        if (objDorStu == null) {
            return dorStuRepository.save(dorStu);
        }
        dorStuRepository.deleteByDIdAndSId(objDorStu.getDId(),objDorStu.getSId());
        return dorStuRepository.save(dorStu);
    }

    /**
     * 删除一个记录
     *
     * @param dId
     * @param sId
     */
    @Transactional(rollbackFor = DorStuException.class)
    public void deleteRelationShip(String dId, String sId) {
        String key="stu:"+dId;
        if (client.isExistKey(key)){
            client.deleteValue(key,studentRepository.queryBySId(sId));
        }

        DorStu objDorStu=dorStuRepository.queryByDIdAndSId(dId,sId);
        if(objDorStu==null){
           throw new DorStuException(DorStuEnum.NOT_THIS_RELATIONSHIP);
        }
        dorStuRepository.deleteByDIdAndSId(dId, sId);
    }
}
